package com.zixuan.sina.utils;

import com.alibaba.fastjson.JSON;
import com.zixuan.sina.entity.Permission;
import com.zixuan.sina.entity.User;
import com.zixuan.sina.entity.vo.Meta;
import com.zixuan.sina.service.PermissionService;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 树形菜单工具类
 */
@Component
public class MenuUtils {
    @Resource
    private PermissionService permissionService;

    /**
     * 根据当前登录用户生成菜单数据
     * @return
     */
    public List<Permission> generateMenu() {
        List<Permission> result = new ArrayList<>();
        User principal = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (principal == null) {
            throw new RuntimeException("未登录");
        }
        String id = principal.getId();
        List<Permission> permissionList = permissionService.findPermissionByUserId(id);
//        Permission permission = new Permission();
//        permission.setLabel("顶级菜单");
//        permission.setParentId(0L);
//        permission.setId(1L);
//        permission.setCode("sys:first");
//        permissionList.add(permission);
//        permissionList=permissionList.stream().distinct().collect(Collectors.toList());
        result = getMenu(permissionList,0L);

        return result;
    }



    private static List<Permission> getMenu(List<Permission> menuList, long pid) {
        List<Permission> result=new ArrayList<>();
        for (Permission permission : menuList) {
            if(permission!=null && permission.getParentId()==pid){
                Meta meta = new Meta();
                if(permission.getRemark()!=null &&"1".equals(permission.getRemark())){
                    meta.setHidden(true);
                }else {
                    meta.setHidden(false);
                }
                permission.setMeta(meta);
                permission.setChildren(getMenu(menuList,permission.getId()));
                result.add(permission);
            }
        }

        return result;
    }


}
